package com.job.client.posts.service.impl;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.job.client.common.result.AppHttpCode;
import com.job.client.common.result.ResponseResult;
import com.job.client.common.utils.JwtTokenUtils;
import com.job.client.model.auth.pojo.User;
import com.job.client.model.company.pojo.Company;
import com.job.client.model.posts.constant.PageConstant;
import com.job.client.model.posts.constant.PostsStatusConstant;
import com.job.client.model.posts.pojo.Category;
import com.job.client.model.posts.pojo.Posts;
import com.job.client.model.rabbitmq.AuditConstant;
import com.job.client.model.rabbitmq.DraftConstant;
import com.job.client.posts.mapper.CategoryMapper;
import com.job.client.posts.mapper.PostsMapper;
import com.job.client.posts.service.PostsService;
import com.job.feign.client.auth.AuthFeign;
import com.job.feign.client.company.CompanyFeign;
import com.mysql.cj.util.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 职位的详细信息表 服务实现类
 * </p>
 *
 * @author fkl
 * @since 2023-12-07
 */
@Service
public class PostsServiceImpl extends ServiceImpl<PostsMapper,Posts> implements PostsService{
    @Autowired
    private PostsMapper postsMapper;
    @Autowired
    private CompanyFeign companyFeign;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AuthFeign authFeign;

    @Override
//    TODO
    public ResponseResult savePosts(Posts posts, HttpServletRequest request) {
        // 数据验证
        if(posts==null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        // 获得用户信息
        ResponseResult responseResult = getUserInfo(request);
        if(responseResult.getCode()!=200){
            return responseResult;
        }
        // 验证用户是否被认证
        User user = JSON.parseObject(JSON.toJSONString(responseResult.getData()), User.class);
        ResponseResult result = companyFeign.userIsAuth(user.getUserId());
        String userId = user.getUserId();
        Map<String,String> data = new HashMap<>();

        data.put("userId",userId);

        if(result.getCode()!=200){
            // 如果未认证，就把保存的id通过mq发送到草稿箱队列
            // 先保存
            postsMapper.insert(posts);
            data.put("postsId",posts.getPostsId());
            String dataJSON = JSON.toJSONString(data);
            rabbitTemplate.convertAndSend(DraftConstant.EXCHANGE_DRAFT, DraftConstant.ROUTINGKEY_POSTS,dataJSON);
            return result;
        }
        // 认证了
        Company company = JSON.parseObject(JSON.toJSONString(result.getData()), Company.class);
        String companyId = company.getCompanyId();
        posts.setCompanyId(companyId);
        posts.setStatus(PostsStatusConstant.UNDER_REVIEW);
        postsMapper.insert(posts);
        data.put("postsId",posts.getPostsId());
        String dataJSON = JSON.toJSONString(data);
        rabbitTemplate.convertAndSend(AuditConstant.EXCHANGE_AUDIT, AuditConstant.ROUTINGKEY_POSTS,dataJSON);
        return ResponseResult.OkResult();
    }

    @Override
    public ResponseResult getPostsInfo(String postsId) {
        if(postsId.charAt(0) == '"'){
            postsId = postsId.substring(1,postsId.length()-1);
        }
        if(postsId == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        Posts posts = postsMapper.selectById(postsId);
        if(posts == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_ERROR);
        }
        Category category = categoryMapper.selectById(posts.getCategoryId());
        if(category == null){
            return ResponseResult.ErrorResult(AppHttpCode.SERVICE_ERROR);
        }
        posts.setCategoryName(category.getName());
        return ResponseResult.OkResult(posts);
    }

    @Override
    public ResponseResult getByCompanyId(String companyId) {
        if(companyId == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        QueryWrapper<Posts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",companyId);
        List<Posts> postsList = postsMapper.selectList(queryWrapper);
        return ResponseResult.OkResult(postsList);
    }

    @Override
    public ResponseResult getByCompanyIdByPage(String companyId, Integer page, Integer size) {
        if(companyId == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        if(page == null){
            page = PageConstant.PAGE;
        }
        if(size == null){
            size = PageConstant.SIZE;
        }
        Page<Posts> data = new Page<>(page,size);
        QueryWrapper<Posts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",companyId);
        postsMapper.selectPage(data,queryWrapper);
        return ResponseResult.OkResult(data);
    }

    @Override
    public ResponseResult getAllInfoList(List<String> postsIds) {
        List<Posts> postsList = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        List<Company> companyList = new ArrayList<>();
        for (String postsId : postsIds) {
            ResponseResult result_posts = getPostsInfo(postsId);
            if(result_posts.getCode() != 200){
                return result_posts;
            }
            Posts posts = JSON.parseObject(JSON.toJSONString(result_posts.getData()), Posts.class);
            ResponseResult result_auth = authFeign.getUserInfoById(posts.getPublisherId());
            if(result_auth.getCode() != 200){
                return result_auth;
            }
            ResponseResult result_company = companyFeign.getCompanyById(posts.getCompanyId());
            if(result_company.getCode() != 200){
                return result_company;
            }
            postsList.add(posts);
            userList.add(JSON.parseObject(JSON.toJSONString(result_auth.getData()),User.class));
            companyList.add(JSON.parseObject(JSON.toJSONString(result_company.getData()),Company.class));
        }
        Map<String, Object> data = new HashMap<>();
        data.put("postsInfoList",postsList);
        data.put("userInfoList",userList);
        data.put("companyInfoList",companyList);
        return ResponseResult.OkResult(data);
    }

    @Override
    public ResponseResult getByUserIdByPage(String userId, Integer page, Integer size) {
        if(userId == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        if(page == null){
            page = PageConstant.PAGE;
        }
        if(size == null){
            size = PageConstant.SIZE;
        }
        Page<Posts> data = new Page<>(page,size);
        QueryWrapper<Posts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publisher_id",userId);
        postsMapper.selectPage(data,queryWrapper);
        return ResponseResult.OkResult(data);
    }

    @Override
    public ResponseResult getCountByCompanyId(String companyId) {
        if(companyId == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        QueryWrapper<Posts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",companyId);
        Long count = postsMapper.selectCount(queryWrapper);
        return ResponseResult.OkResult(count);
    }

    // 根据token获得用户信息
    public ResponseResult getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        // token为”“或者null则未登录
        if(StringUtils.isNullOrEmpty(token)){
            return ResponseResult.ErrorResult(AppHttpCode.LOGIN_AUTH);
        }
        User user = JwtTokenUtils.checkToken(token);
        // 其中有数据缺失则表示token被修改
        if(user.getUserId()==null || (user.getUsername()==null && user.getPhone()==null)){
            return ResponseResult.ErrorResult(AppHttpCode.TOKEN_ERROR);
        }
        return ResponseResult.OkResult(user);
    }
}
